package info.mykhaylov.mvc.controllers;

import info.mykhaylov.entities.Login;
import info.mykhaylov.mvc.services.DataService;
import lombok.EqualsAndHashCode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("/data/{datumName}")
public class Data {

	private enum SupportedData {
		USERS(Login.class);

		private final Class classType;

		<T> SupportedData(Class<T> classType){
			this.classType = classType;
		}

		public <T> Class<T> getClassType() {
			return classType;
		}
	}

	@XmlRootElement
	@lombok.Data
	@EqualsAndHashCode(exclude = {"isSuccess"})
	public static class Response<T> {
		private final boolean isSuccess;

		@NotNull
		private final List<? extends T> data;
	}

	@Autowired
	private DataService dataService;

	@NotNull
	@RequestMapping(
		method = RequestMethod.GET,
		headers = {
			"Content-Type=application/json",
			"Accept=application/json"
		}
	)
	@ResponseBody
	public <T> Response<T> readData(
		final @NotNull @PathVariable("datumName") String datumName,
		final @RequestParam int page,
		final @RequestParam int start,
		final @RequestParam int limit
	) {
		@Nullable final SupportedData supportedData = Enum.valueOf(SupportedData.class, datumName.toUpperCase());
		final boolean isSuccess;
		@NotNull final List<? extends T> data;

		if (null == supportedData) {
			isSuccess = false;

			data = new LinkedList<T>();
		} else {
			isSuccess = true;
			data = dataService.readAll(supportedData.<T>getClassType());
		}

		return new Response<T>(isSuccess, data);
	}
}
